package com.guaoran.source.zookeeper.demo;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @author : 孤傲然
 * @Description :
 *  事件机制
 * @date :2018/6/12 18:29
 */
public class WatchDemo {
    public static void main(String[] args) {
        final CountDownLatch countDownLatch = new CountDownLatch(1);
        try {
            ZooKeeper zooKeeper =
                    new ZooKeeper("192.168.45.131:2181", 4000, new Watcher() {
                        @Override
                        public void process(WatchedEvent event) {
                            if(Event.KeeperState.SyncConnected==event.getState()){
                                //如果是连接响应
                                countDownLatch.countDown();
                            }
                            System.out.println("默认事件："+event.getType());
                        }
                    });
            countDownLatch.await();
            //创建节点,开放式的ACL,持久化节点
            zooKeeper.create("/demo", "demo".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

            zooKeeper.exists("/demo", new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    System.out.println("内部watcher:"+event.getType()+":"+event.getPath());
                    try {
                        zooKeeper.exists(event.getPath(),true);
                    } catch (KeeperException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            Stat stat = new Stat();
            stat = zooKeeper.setData("/demo", "guaoran".getBytes(), stat.getVersion());
            zooKeeper.delete("/demo",stat.getVersion());
            zooKeeper.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (KeeperException e) {
            e.printStackTrace();
        }
    }
}
